package nivod

import (
	"github.com/gogf/gf/v2/encoding/gjson"
	"time"
	"uni-crawl-frame/core"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/utils/browsermob"
	"uni-crawl-frame/utils/constant"
	"uni-crawl-frame/utils/ffmpegutil"
	"uni-crawl-frame/utils/httputil"
)

type NiVodCrawl struct {
	*core.AbstractCrawlVodFlow
}

func (r *NiVodCrawl) OpenBrowser(ctx *core.ApplicationContext) {
	_ = ctx.Wd.Get(ctx.CrawlQueueSeed.CrawlSeedUrl)
	checkLoadSuccess(ctx, constant.LocalRefresh)
}

func checkLoadSuccess(ctx *core.ApplicationContext, retry int) {
	time.Sleep(time.Second * 5)
	request := getM3U8Request(ctx)
	if request == nil && retry > 0 {
		_ = ctx.Wd.Refresh()
		checkLoadSuccess(ctx, retry-1)
	}
}

func (r *NiVodCrawl) FillTargetRequest(ctx *core.ApplicationContext) {
	request := getM3U8Request(ctx)
	if request != nil {
		ctx.CrawlQueueSeed.CrawlM3U8Url = request.Get("url").String()
	}
}

func getM3U8Request(ctx *core.ApplicationContext) *gjson.Json {
	return browsermob.GetHarRequestLocalRetry(ctx.XClient, "mud.m3u8", "")
}

func (r *NiVodCrawl) ConvertM3U8(seed *entity.CmsCrawlQueue, filePath string) (*ffmpegutil.M3u8DO, error) {
	baseUrl := r.ConvertM3U8GetBaseUrl(seed.CrawlM3U8Url)
	return ffmpegutil.ConvertM3U8(seed.CrawlSeedUrl, baseUrl, filePath)
}

func (r *NiVodCrawl) ConvertM3U8GetBaseUrl(m3u8Url string) string {
	return httputil.GetBaseUrlByBackslash(m3u8Url)
}
